package ourfilter;

import interfaces.Readable;
import interfaces.Writeable;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.StreamCorruptedException;
import java.security.InvalidParameterException;
import java.util.HashMap;
import java.util.StringTokenizer;

import pipes.Pipe;
import TransferObjekts.Word;
import filter.AbstractFilter;

public class IgnoreWordFilter extends AbstractFilter<Word, Word> {

	private String path = "en.txt";
	private BufferedReader br = null;
	private Readable<Word> in;
	private Writeable<Word> out;
	private HashMap<String, String> ignoredWords;

	public IgnoreWordFilter(Pipe<Word> in, Pipe<Word> out) throws InvalidParameterException {
		super(in, out);
		in.setOut(this);
		out.setIn(this);
		this.in = in;
		this.out = out;
		readWordsFromFile();
	}

	public void readWordsFromFile() {
		ignoredWords = new HashMap<String, String>();

		String line = "";
		String word = "";
		try {
			if (br == null) {
				br = new BufferedReader(new FileReader(this.path));
			}

			while ((line = br.readLine()) != null) {
				StringTokenizer st = new StringTokenizer(line);
				word = st.nextToken();
				ignoredWords.put(word.toLowerCase(), word.toLowerCase());
			}

		} catch (IOException io) {
			io.printStackTrace();
		}
	}

	private boolean checkForIgnoration(String value) {
		if (ignoredWords.containsValue(value.toLowerCase())) {
			return true;
		}
		return false;
	}

	@Override
	public Word read() throws StreamCorruptedException {
		Word w = null;
		do {
			w = in.read();
			if (w == null) {
				return null;
			}
		} while (checkForIgnoration(w.getWord()));
		return w;
	}

	@Override
	public void write(Word w) throws StreamCorruptedException {
		if (w != null) {
			if (!checkForIgnoration(w.getWord())) {
				out.write(w);
			}
		}else{
			out.write(null);
		}
	}

	@Override
	public void run() {
	}

}
